package ltd.trackan.messagecenter.utils;


import lombok.extern.log4j.Log4j2;
import ltd.trackan.messagecenter.model.entity.EmailModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Log4j2
@Component
public class SendMailMessageUtils {
    
    /**
     * 发送者地址
     **/
    @Value("${spring.mail.send}")
    private String posterAddress;
    
    @Resource
    JavaMailSender sender;
    
    @Resource
    JavaMailSenderImpl javaMailSenderImpl;
    
    /**
     * 文本发送
     **/
    public void sendEmailAsText(final EmailModel emailModel) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(emailModel.getEmailTheme());
        message.setText(emailModel.getEmailContent());
        message.setFrom(posterAddress);
        message.setTo(emailModel.getReceiverEmailAddress());
        sender.send(message);
    }
    
    /**
     * html 网页发送
     * 该方法为同步方法
     **/
    public Boolean sendEmailAsSysExceptionHtml(final EmailModel emailModel) {// 用final关键字修饰的变量，只能进行一次赋值操作，并且在生存期内不可以改变它的值。
        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
        MimeMessageHelper mimeMessageHelper;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setSubject(emailModel.getEmailTheme());
            mimeMessageHelper.setFrom(posterAddress);
            mimeMessageHelper.setTo(emailModel.getReceiverEmailAddress());
            mimeMessageHelper.setText(emailModel.getEmailContent(), true);
            
            sender.send(mimeMessage);
            log.info("邮件已发送至[{}]邮箱！", emailModel.getReceiverEmailAddress());
            return true;
        } catch (MessagingException e) {
            log.error("邮件发送失败：{}", e.getMessage());
            return false;
        } catch (MailException e) {
            log.error("邮箱异常：{}", e.getMessage());
            return false;
        }
    }
}